<template>
  <BoTable
    :columns="columns"
    :request="_getDeviceList"
    ref="tableRef"
    :row-selection="rowSelection"
    row-key="deviceId"
    :show-index="true"
  >
    <template #toolbars>
      <Space :size="8">
        <!-- <ImportModel @import-after="() => tableRef.refresh()"></ImportModel> -->
        <Button type="primary" :disabled="!selectKeys.length" @click="onDelete">
          删除
        </Button>
        <Button @click="onReset" :disabled="!selectKeys.length">重启</Button>
      </Space>
    </template>
  </BoTable>
  <!-- 详情弹窗 -->
  <FormModal :columns="items" :model="model" ref="formModalRef">
    <!-- <template #map>
      <div :id="id" class="map-container h-[400px] w-[100%]"></div>
    </template> -->
    <!-- <template #footer="{ submit }" v-if="isValid">
      <Space>
        <Button @click="onCancel"> 取消 </Button>
        <Button type="primary" danger @click="onRefuse(submit)"> 拒绝 </Button>
        <Button type="primary" @click="onPass(submit)"> 通过 </Button>
      </Space>
    </template> -->
  </FormModal>
  <!-- 参数查看弹窗 -->
  <ParamsModal
    v-if="openParamsModal"
    v-model:value="openParamsModal"
    :tableRef="tableRef"
    :stationId="stationId"
  />
  <!-- 重启 弹窗 -->
  <SseModal />
</template>
<route lang="json">
{
  "name": "device-list",
  "meta": {
    "title": "设备列表"
  }
}
</route>
<script setup lang="tsx">
import { computed, nextTick, ref, useId } from 'vue';
import {
  getDeviceManufacturerSelect,
  getDeviceModelSelect,
  getDevicePowerSelect,
  getDeviceProjectSelect,
} from '@/api';
import { createOlMap, useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { listToEnum, listToOption } from '@boeyo/shared';
import { BoFormProps, BoTable, BoTableProps } from '@boeyo/ui';
import { Button, DatePicker, Modal, Space, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import LonLat from '@/components/LonLat/index.vue';
import { useSseModal } from '@/hooks/useSseModal';
import { deviceEnum } from '../constants';
import { checkDevice, deleteDevice, getDeviceList, updateDevice } from './api';
import ParamsModal from './components/ParamsModal.vue';

const _getDeviceList = async (params: any) => {
  const res: any = await getDeviceList(params);
  res.rows = res.rows.map((item: any) => {
    item.latitude = (+item.latitude || 0).toFixed(4);
    item.longitude = (+item.longitude || 0).toFixed(4);
    item.pLatitude = (+item.pLatitude || 0).toFixed(4);
    item.pLongitude = (+item.pLongitude || 0).toFixed(4);
    return item;
  });
  return {
    rows: res.rows,
    total: res.total,
  };
};

const tableRef = ref();
const selectKeys = ref<any[]>([]);
const selectedRows = ref([]);
// 查看参数
const stationId = ref(0);
// 设置重启参数
const stationIds = computed(() => {
  return selectedRows.value.map((item) => item.stationId);
});
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values, _selectedRows) {
      selectKeys.value = values;
      selectedRows.value = _selectedRows;
    },
  };
});

const { SseModal, open: openSse } = useSseModal();
const onReset = () => {
  Modal.confirm({
    title: '警告',
    content: '确认重启设备？',
    onOk() {
      openSse({
        title: '重启设备',
        url: '/api/edge/sse/reset',
        data: stationIds,
        onClose() {
          selectKeys.value = selectedRows.value = [];
          tableRef.value.refresh();
        },
      });
    },
  });
};

// 获取表单下拉框数据
const mnufacturerOptions = ref<any[]>([]);
const manufacturerEnum = ref<Record<string, any>>({});
const projectOptions = ref<any[]>([]);
const projectEnum = ref<Record<string, any>>({});
const powerOptions = ref<any[]>([]);
const powerEnum = ref<Record<string, any>>({});
const modelOptions = ref<any[]>([]);
const modelEnum = ref<Record<string, any>>({});

const openParamsModal = ref(false);
const init = () => {
  getDeviceManufacturerSelect(deviceEnum.SEISMOGRAPH).then(({ data }) => {
    mnufacturerOptions.value = listToOption(data, 'name', 'facId');
    manufacturerEnum.value = listToEnum(data, 'name', 'facId');
  });
  getDeviceProjectSelect().then(({ data }) => {
    projectOptions.value = listToOption(data, 'name', 'projectId');
    projectEnum.value = listToEnum(data, 'name', 'projectId');
  });
  getDevicePowerSelect().then(({ data }) => {
    powerOptions.value = listToOption(data, 'powerSupplyName', 'id');
    powerEnum.value = listToEnum(data, 'powerSupplyName', 'id');
  });
};
init();

const dictArr = [
  'device_type',
  'check_status',
  'online_status',
  'use_status',
  'flag_status',
];
const {
  deviceTypeEnum,
  onlineStatusEnum,
  checkStatusEnum,
  useStatusEnum,
  flagStatusEnum,
  flagStatusOptions,
  deviceTypeOptions,
} = useDicts(dictArr);

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
  },
  {
    title: '设备编号',
    dataIndex: 'stationId',
  },
  {
    title: '所属边缘',
    dataIndex: 'edgeCode',
    hideInSearch: true,
  },
  {
    title: '接入时间',
    dataIndex: 'accessTime',
    hideInSearch: true,
  },
  // {
  //   title: '校验时间',
  //   dataIndex: 'checkTime',
  //   hideInSearch: true,
  // },
  // {
  //   title: '效验状态', //（0未效验 1已效验 2已拒绝）
  //   dataIndex: 'checkStatus',
  //   valueEnum: checkStatusEnum.value,
  //   valueType: 'status',
  //   hideInSearch: true,
  // },
  {
    title: '数据端在线状态', //(0离线 1在线)
    dataIndex: 'dataOnlineStatus',
    valueEnum: onlineStatusEnum.value,
    valueType: 'status',
  },
  {
    title: '管理端在线状态', //(0离线 1在线)
    dataIndex: 'adminOnlineStatus',
    valueType: 'status',
    valueEnum: onlineStatusEnum.value,
  },

  {
    title: '触发端在线状态', //(0离线 1在线)
    dataIndex: 'triggerOnlineStatus',
    valueEnum: onlineStatusEnum.value,
    valueType: 'status',
  },
  // {
  //   title: '设备状态', //（0正常 1停用）
  //   dataIndex: 'status',
  //   valueType: 'status',
  //   valueEnum: useStatusEnum.value,
  //   hideInSearch: true,
  // },
  {
    title: '日志下载', //（0正常 1停用）
    dataIndex: '_log',
    fixed: 'right',
    hideInSearch: true,
    customRender({ record }) {
      return (
        <DatePicker
          disabledDate={(currentDate) => dayjs().isBefore(currentDate)}
          onChange={(e) => {
            if (!e) return;
            const { stationId } = record;
            const date = dayjs(e).format('YYYYMMDD');
            const data = [{ stationId, date }];
            openSse({
              title: '日志下载',
              data,
              url: '/api/edge/sse/downLogFile',
            });
          }}
        ></DatePicker>
      );
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions({ record }) {
      return [
        {
          text: '编辑',
          onClick(record) {
            onEdit(record);
          },
        },
        // {
        //   text: '校验',
        //   disabled: record.checkStatus !== '0',
        //   onClick(record) {
        //     onCheck(record);
        //   },
        // },
        {
          text: '参数',
          disabled: record.deviceCode && record.adminOnlineStatus == '1',
          onClick(record) {
            openParamsModal.value = true;
            stationId.value = record.stationId;
          },
        },
      ];
    },
  },
]);

const items = computed<BoFormProps['columns']>(() => [
  {
    title: '',
    dataIndex: 'baseInfo',
    valueType: 'input',
    colProps: { span: 24 },
    formItemRender(state) {
      return <div class='module-title'>设备基本信息</div>;
    },
  },
  {
    title: '台网代码',
    dataIndex: 'networkCode',
    valueType: 'input',
    render(state) {
      return <div>{state.networkCode}</div>;
    },
  },
  {
    title: '台站代码',
    dataIndex: 'stationCode',
    valueType: 'input',
    render(state) {
      return <div>{state.stationCode}</div>;
    },
  },
  {
    title: '软件版本/型号',
    dataIndex: 'version',
    valueType: 'input',
    render(state) {
      return <div>{state.version}</div>;
    },
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
    valueType: 'input',
    render(state) {
      return <div>{state.deviceCode}</div>;
    },
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择设备类型',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请选择设备类型',
      disabled: true,
      options: deviceTypeOptions.value as any,
    },
  },
  {
    title: '设备厂商',
    dataIndex: 'facId',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择设备厂商',
          trigger: 'blur',
        },
      ],
    },
    fieldProps(state) {
      return {
        placeholder: '请选择设备厂商',
        options: mnufacturerOptions.value,
        onChange(facId) {
          getDeviceModelSelect({ facId: facId as number, type: 1 }).then(
            ({ data }) => {
              modelOptions.value = listToOption(data, 'model', 'modelId');
              modelEnum.value = listToEnum(data, 'model', 'modelId');
              state.modelId = undefined;
            },
          );
        },
      };
    },
  },
  {
    title: '设备型号',
    dataIndex: 'modelId',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择设备型号',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请选择设备型号',
      options: modelOptions.value,
    },
  },
  {
    title: '',
    dataIndex: 'validInfo',
    valueType: 'input',
    colProps: { span: 24 },
    formItemRender(state) {
      return <div class='module-title'>校验信息</div>;
    },
  },

  {
    title: '认证密码',
    dataIndex: 'password',
    valueType: 'password',
    // formItemProps: {
    //   rules: [
    //     {
    //       required: true,
    //       message: '请输入认证密码',
    //       trigger: 'blur',
    //     },
    //   ],
    // },
    fieldProps: {
      placeholder: '请输入认证密码',
      disabled: true,
      visible: true,
    },
  },
  {
    title: '供电设备',
    dataIndex: 'powerSupplyId',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择供电设备',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请选择供电设备',
      options: powerOptions.value,
    },
  },
  // {
  //   title: '是否备份数据',
  //   dataIndex: 'copyDataFile',
  //   valueType: 'radio',
  //   formItemProps: {
  //     rules: [
  //       {
  //         required: true,
  //         message: '请选择是否备份数据',
  //         trigger: 'blur',
  //       },
  //     ],
  //   },
  //   fieldProps: {
  //     placeholder: '请选择是否备份数据',
  //     options: flagStatusOptions.value,
  //   },
  // },
  // {
  //   title: '设备ip',
  //   dataIndex: 'ip',
  //   valueType: 'input',
  //   formItemProps: {
  //     rules: [
  //       {
  //         required: true,
  //         message: '请输入设备ip',
  //         trigger: 'blur',
  //       },
  //     ],
  //   },
  //   fieldProps: {
  //     placeholder: '请输入设备ip',
  //   },
  //   hidden: (state) => state.copyDataFile !== '0',
  // },
  // {
  //   title: 'FTP端口',
  //   dataIndex: 'ftpPort',
  //   valueType: 'input',
  //   formItemProps: {
  //     rules: [
  //       {
  //         required: true,
  //         message: '请输入FTP端口',
  //         trigger: 'blur',
  //       },
  //     ],
  //   },
  //   fieldProps: {
  //     placeholder: '请输入FTP端口',
  //   },
  //   hidden: (state) => state.copyDataFile !== '0',
  // },
  // {
  //   title: 'FTP用户名',
  //   dataIndex: 'ftpUsername',
  //   valueType: 'input',
  //   formItemProps: {
  //     rules: [
  //       {
  //         required: true,
  //         message: '请输入FTP用户名',
  //         trigger: 'blur',
  //       },
  //     ],
  //   },
  //   fieldProps: {
  //     placeholder: '请输入FTP用户名',
  //   },
  //   hidden: (state) => state.copyDataFile !== '0',
  // },
  // {
  //   title: 'FTP密码',
  //   dataIndex: 'ftpPassword',
  //   valueType: 'input',
  //   formItemProps: {
  //     rules: [
  //       {
  //         required: true,
  //         message: '请输入FTP密码',
  //         trigger: 'blur',
  //       },
  //     ],
  //   },
  //   fieldProps: {
  //     placeholder: '请输入FTP密码',
  //   },
  //   hidden: (state) => state.copyDataFile !== '0',
  // },
  // {
  //   title: 'FTP数据存放文件夹',
  //   dataIndex: 'ftpWorkDir',
  //   valueType: 'input',
  //   formItemProps: {
  //     rules: [
  //       {
  //         required: true,
  //         message: '请输入FTP数据存放文件夹',
  //         trigger: 'blur',
  //       },
  //     ],
  //   },
  //   fieldProps: {
  //     placeholder: '请输入FTP数据存放文件夹',
  //   },
  //   hidden: (state) => state.copyDataFile !== '0',
  // },
  // {
  //   title: '所属项目',
  //   dataIndex: 'projectId',
  //   valueType: 'select',
  //   formItemProps: {
  //     rules: [
  //       {
  //         required: true,
  //         message: '请选择所属项目',
  //         trigger: 'blur',
  //       },
  //     ],
  //   },
  //   fieldProps: {
  //     placeholder: '请选择所属项目',
  //     options: projectOptions.value as any,
  //   },
  // },
  // {
  //   title: '省',
  //   dataIndex: 'province',
  //   valueType: 'select',
  //   fieldProps: {
  //     placeholder: '请选择省',
  //   },
  // },
  // {
  //   title: '市',
  //   dataIndex: 'city',
  //   valueType: 'select',
  //   fieldProps: {
  //     placeholder: '请选择市',
  //   },
  // },
  // {
  //   title: '区',
  //   dataIndex: 'area',
  //   valueType: 'select',
  //   fieldProps: {
  //     placeholder: '请选择区',
  //   },
  // },
  {
    title: '详细地址',
    dataIndex: 'address',
    valueType: 'input',
    fieldProps: {
      placeholder: '请输入详细地址',
    },
  },
  {
    title: '设备返回经度',
    dataIndex: 'longitude',
    valueType: 'input',
    fieldProps: {
      placeholder: '请输入经度',
      disabled: true,
    },
  },
  {
    title: '设备返回纬度',
    dataIndex: 'latitude',
    valueType: 'input',
    fieldProps: {
      placeholder: '请输入纬度',
      disabled: true,
    },
  },
  {
    title: '平台经纬度',
    dataIndex: 'pLongitude',
    valueType: 'input',
    formItemProps: {
      rules: [{ required: true, message: '请输入经度' }],
    },
    fieldProps: {
      placeholder: '请输入经度',
    },
    render(state) {
      return (
        <LonLat v-model:lon={state.pLongitude} v-model:lat={state.pLatitude} />
      );
    },
  },
  // {
  //   title: '平台经度',
  //   dataIndex: 'pLongitude',
  //   valueType: 'inputNumber',
  //   fieldProps: {
  //     placeholder: '请输入经度',
  //   },
  // },
  // {
  //   title: '平台纬度',
  //   dataIndex: 'pLatitude',
  //   valueType: 'inputNumber',
  //   fieldProps: {
  //     placeholder: '请输入纬度',
  //   },
  // },
]);

const model = ref<any>({});
console.log(model.value, 'model');

const { FormModal, open, close } = useFormModal({
  size: 'middle',
  column: 2,
  formProps: {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 18,
    },
  },
});

const onDelete = () => {
  const ids = selectKeys.value;
  if (!ids.length) return;
  Modal.confirm({
    title: '系统提示',
    content: `确认要删除当前选中项数据？`,
    centered: true,
    onOk: async () => {
      await deleteDevice(ids);
      selectKeys.value = [];
      tableRef.value.refresh();
      message.success('操作成功');
    },
  });
};

// 渲染地图
// 地图相关
// const id = useId();
// const { useOl } = createOlMap();
// const {
//   renderTile, // mounted 后调用绘制地图
//   renderFeature, // 绘制 feature
//   removeFeature, // 删除 feature
//   animate, // 平滑移动中心点
// } = useOl({
//   target: id, // 地图挂载节点
//   zoom: 12, // 地图层级
//   maxZoom: 18, // 最大层级
//   tileUrl: VITE_MAP_URL, // 瓦片地址
//   onClick({ lonLat }) {
//     // 点击事件， 如果点击 feature， 会将 绘制的 feature 中 data 传回来
//     model.value.pLongitude = lonLat[0];
//     model.value.pLatitude = lonLat[1];
//     renderMap(lonLat);
//   },
// });

/**
 * 编辑
 * @param record
 */
const onEdit = (record: any) => {
  // model的优先级高于defaultValue
  model.value = {
    ...model.value,
    ...record,
  };

  // 根据facId获取model型号下拉框数据
  getDeviceModelSelect({ facId: record.facId as number, type: 1 }).then(
    ({ data }) => {
      modelOptions.value = listToOption(data, 'model', 'modelId');
      modelEnum.value = listToEnum(data, 'model', 'modelId');
    },
  );

  open({
    title: (type) => (type === 'info' ? '详情' : '处理'),
    modalType: 'info',
    request: async (params: any) => {
      await updateDevice(model.value);
      tableRef.value.refresh();
    },
  });

  // nextTick(() => {
  //   // 渲染瓦片
  //   renderTile();
  //   // 移动中心点
  //   renderMap([record.pLongitude, record.pLatitude]);
  // });
};

// const renderMap = (center: Array<number>[]) => {
//   // 清除原有坐标点
//   removeFeature();
//   animate({
//     center, //布局问题保证中心点偏移
//     duration: 100,
//   });
//   // 绘制坐标点
//   renderFeature({
//     lonLat: center,
//     style: {
//       image: {
//         src: '/static/access/mark-params.png',
//         scale: 0.8,
//       },
//     },
//   });
// };

/**
 * 校验
 * @param record
 */
// 点击了校验按钮标识
const isValid = ref(false);
const formModalRef = ref();
const onCheck = (record: any) => {
  console.log(record, 'record');

  isValid.value = true;
  // model的优先级高于defaultValue
  model.value = {
    ...model.value,
    ...record,
  };
  open({
    title: '校验',
    request: async (params: any) => {
      await checkDevice(model.value);
      tableRef.value.refresh();
    },
  });

  // nextTick(() => {
  //   // 渲染瓦片
  //   renderTile();
  //   // 移动中心点
  //   renderMap([record.pLongitude, record.pLatitude]);
  // });
};

const onCancel = () => {
  isValid.value = false;
  close();
};

const onRefuse = async (submit: Function) => {
  model.value.checkStatus = '2';
  submit();
  tableRef.value.refresh();
};
const onPass = async (submit: Function) => {
  model.value.checkStatus = '1';
  submit();
  tableRef.value.refresh();
};

// const beforeConnect = () => {
//   return new Promise((resolve, reject) => {});
// };

// const onCloseSseModal = () => {
//   selectKeys.value = selectedRows.value = [];
//   tableRef.value.refresh();
// };
</script>

<style lang="scss" scoped></style>
